package http.observer.impl;

import http.executor.ResponseExecutor;
import http.observer.Observer;
import http.util.FullHttpResponseUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.HttpResponseStatus;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAccessor;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

public class ContextMapObserver implements Observer {
    static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
    private static int TIME_OUT=10;
    private static volatile boolean isNeetCheck=false;



    private static void exec() {
        TimerTask task=new TimerTask() {
            @Override
            public void run() {
                for(Map.Entry<String, ChannelHandlerContext> entry : ResponseExecutor.getContextMap().entrySet()){
                    if(ContextMapObserver.isTimeOut(entry.getKey())){
                        ResponseExecutor.getContextMap().remove(entry.getKey());
                        FullHttpResponseUtil.response(HttpResponseStatus.REQUEST_TIMEOUT,"time_out",entry.getValue());
                    }
                }
            }
        };
        Timer timer = new Timer();
        timer.schedule(task,0,10 * 1000);
    }


    @Override
    public void update(String id) {
        if(!isNeetCheck){
            isNeetCheck=true;
            exec();
        }
    }

    private static  boolean isTimeOut(String id){
        try {
            TemporalAccessor startTime = formatter.parse(id.substring(0,id.length()-7));
            Duration duration = Duration.between(LocalDateTime.from(startTime), LocalDateTime.now());
            return duration.getSeconds() > TIME_OUT;
        }catch (Exception e){
            e.printStackTrace();
        }
        return true;
    }



}
